﻿using CoreModule;
using Microsoft.Extensions.Logging;
using Prism.Ioc;
using Prism.Modularity;
using ResourceLocalization;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using WPFLocalizeExtension.Engine;
using Yuwell.BloodGlucose.BluetoothDataParser.App.Views;
namespace Yuwell.BloodGlucose.BluetoothDataParser.App
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {

        /// <summary>
        /// 当前使用的
        /// </summary>
        public static ResLanguage UsingResLanguage
        {
            get; set;
        } = ResLanguage.None;
        /// <summary>
        /// 
        /// </summary>

        public App()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
            //当某个异常未被捕获时出现
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            //未被观察到的Task多线程异常
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
  
        }

        Mutex SingleMutex { get; set; }
   /// <summary>
   /// 
   /// </summary>
   string Args { get; set; }
        protected override void OnStartup(StartupEventArgs e)
        {
            //2 WPF单例程序：方案2,Mutex类
            bool createNew;
            SingleMutex = new Mutex(true, Process.GetCurrentProcess().ProcessName, out createNew);
            if (!createNew)
            {
                this.Shutdown();
                return;
            }
             
           Args = string.Join(",", e.Args);


            var resLanguageConfiguration = ResourceLocalization.ResLanguageConfiguration.Load();
            var resLanguage = resLanguageConfiguration.SettingResLanguage; ;

            UsingResLanguage = resLanguage;

            LocalizeDictionary.Instance.SetCurrentThreadCulture = true;
            LocalizeDictionary.Instance.Culture = new CultureInfo(resLanguage.GetDescription());


            base.OnStartup(e);

            //SplashScreen splashScreen = new SplashScreen("Syncing.gif");
            //splashScreen.Show(true,true);
        }
        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            Logger.LogError(e.Exception.Message);
#if DEBUG
            MessageBox.Show("Current_DispatcherUnhandledException:" + (e.Exception.Message));
#endif
            Application.Current.Shutdown();
        }
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Logger.LogError((e.ExceptionObject as Exception).Message);
#if DEBUG
            MessageBox.Show("CurrentDomain_UnhandledException:" + (e.ExceptionObject as Exception).Message);
#endif
            Application.Current.Shutdown();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
        {
            Logger.LogError(e.Exception.Message);
#if DEBUG
            MessageBox.Show("TaskScheduler_UnobservedTaskException:" + (e.Exception.Message));
#endif
            Application.Current.Shutdown();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }
        [NotNull]
        IContainerRegistry ContainerRegistry { get; set; }
        [NotNull]
        Microsoft.Extensions.Logging.ILogger Logger { get; set; }
         
        /// <summary>
        /// 注册 类型
        /// </summary>
        /// <param name="containerRegistry"></param>
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {



        
            ContainerRegistry = containerRegistry;

            var factory = new NLog.Extensions.Logging.NLogLoggerFactory();
            Logger = factory.CreateLogger("NLog");

            containerRegistry.RegisterInstance(Logger);

            base.RegisterRequiredTypes(containerRegistry);
            containerRegistry.RegisterSingleton<IModuleInitializer, AppModuleInitializer>();
     
            containerRegistry.RegisterInstance<IContainerRegistry>(containerRegistry);
            
 
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dateTime"></param>
        private void ClearLog(DateTime expireDateTime)
        {
            var logPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "logs");
            var files = System.IO.Directory.GetFiles(logPath, "*.log");
            foreach (var file in files) {
                var fileInfo = new System.IO.FileInfo(file);
                if (fileInfo.CreationTime<expireDateTime)
                {
                    try
                    {
                        System.IO.File.Delete(file);
                    }
                    catch(Exception e)
                    {
                        Logger.LogInformation(e.Message);
                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnExit(ExitEventArgs e)
        {


            //var deviceManager = Container.Resolve<IDeviceManager>();
            //deviceManager.StopDevice();
         
            try
            {

     
                ClearLog(DateTime.Now.AddDays(-10));
           
              
                NLog.LogManager.Shutdown();
             
            }
            catch (Exception)
            {
     
            }
            finally
            {
                SingleMutex.ReleaseMutex();
            }
          
            base.OnExit(e);
        }
        /// <summary>
        /// 
        /// </summary>
       
        
        protected override void InitializeShell(Window shell)
        {
           
            var notifier = shell as INotifier;
            
            ContainerRegistry.RegisterInstance(notifier);
     
            var windowLifetime = shell.DataContext as IWindowLifetime;
            
            ContainerRegistry.RegisterInstance(windowLifetime);
              
            ContainerRegistry.RegisterInstance(shell.Dispatcher);
             
            base.InitializeShell(shell);
        }
        
        /// <summary>
        /// 
        /// </summary>
        protected override void OnInitialized()
        {
          
            base.OnInitialized();
 

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override IModuleCatalog CreateModuleCatalog()
        {
         
            var modulePath = "Modules";
            if (System.IO.Directory.Exists("Modules")){
                return new AppDirectoryModuleCatalog() { ModulePath = modulePath };
            }
            else
            {
                return base.CreateModuleCatalog();
            }
        }
      
        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleCatalog"></param>
        /// <param name="resLanguage"></param>
        private  void ConfigureResourceLocalizationModule(IModuleCatalog moduleCatalog)
        {
            if (!moduleCatalog.Modules.Any(item => item.ModuleName == "ZhCnResourceModule"))
            {
                moduleCatalog.AddModule<ZhCnResourceModule.Module>("ZhCnResourceModule", InitializationMode.WhenAvailable, "CoreModule", "UIModule");
            }
            if (!moduleCatalog.Modules.Any(item => item.ModuleName == "EnResourceModule"))
            {
                moduleCatalog.AddModule<EnResourceModule.Module>("EnResourceModule", InitializationMode.WhenAvailable, "CoreModule", "UIModule");
            }
            if (!moduleCatalog.Modules.Any(item => item.ModuleName == "DeResourceModule"))
            {
                moduleCatalog.AddModule<DeResourceModule.Module>("DeResourceModule", InitializationMode.WhenAvailable, "CoreModule", "UIModule");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="moduleCatalog"></param>
        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        { 

            ///核心模块
            if (!moduleCatalog.Modules.Any(item => item.ModuleName == "CoreModule"))
            {
                moduleCatalog.AddModule<CoreModule.Module>("CoreModule");
            }
            if (!moduleCatalog.Modules.Any(item => item.ModuleName == "UIModule"))
            {
                moduleCatalog.AddModule<UIModule.Module>("UIModule");
            }

            ConfigureResourceLocalizationModule(moduleCatalog);
             

            base.ConfigureModuleCatalog(moduleCatalog);
        }
       
    }
}
